package cn.lanqiao.facelogin.utils;

import cn.lanqiao.facelogin.domain.SendMsg;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * 2022/2/23 8:54
 *
 * @author HZ
 */
public class SendCodeUtils {

    //验证码临时存储
    public final Map<String, SendMsg> CODE_MAP = new HashMap<>();

    //限制验证码发送次数 （5）
    public final Map<String, SendMsg> SEND_CODE_COUNT_MAP = new HashMap<>();

    /**
     * 发送验证码
     *
//     * @param tel 手机号
     * @return 发送结果，成功返回true，失败返回false
     */
    public boolean sendCode() {
        try {
            String code = getCode();
            System.out.println("验证码:" + code);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 生成验证码
     *
//     * @param tel 手机号
     * @return 验证码
     */
    public String getCode() {
        String code = String.valueOf((int) Math.round((Math.random() * 9 + 1) * 100000));

//        CODE_MAP.put(tel, new SendMsg(code, System.currentTimeMillis(), null));

        return code;
    }

    /**
     * 获取该手机号发送验证码的次数，并限制 1H 之内之内发送 5 次验证码
     *
     * @param tel 手机号
     */
    public void setSendCount(String tel) {
        SendMsg sendMsg = SEND_CODE_COUNT_MAP.get(tel);
        System.out.println(sendMsg);
        if (sendMsg == null) {
            sendMsg = new SendMsg(null, System.currentTimeMillis(), 1);
        } else if (System.currentTimeMillis() - sendMsg.getTime() >= 3600000) {
            sendMsg.setTime(System.currentTimeMillis());
            sendMsg.setCount(1);
        } else {
            if (sendMsg.getCount() <= 4) {
                sendMsg.setCount(sendMsg.getCount() + 1);
            }
        }

        SEND_CODE_COUNT_MAP.put(tel, sendMsg);
    }

    /**
     * 获取该手机号发送验证码的次数
     *
     * @param tel 手机号
     * @return 返回发送验证码次数
     */
    public int getSendCount(String tel) {
        try {
            return SEND_CODE_COUNT_MAP.get(tel).getCount();
        } catch (Exception e) {
//            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 验证码失效
     *
     * @param tel 电话号码
     */
    public void codeInvalidation(String tel) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - CODE_MAP.get(tel).getTime() >= 15000) { //15s
            CODE_MAP.remove(tel);
        }
    }
}
